<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width = device-width , initial-scale = 1 , minimum-scale = 1 , maximum-scale = 1 , user-scalable = no">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="../../resource/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../resource/css/common.css">
</head>
<body>
<div id="header">
    载入中
    <span class=""></span>
</div>
<div class="loading">
    <img src="../../resource/images/loading.jpg" />
</div>
<div class="seller-content">
</div>
<div class="coupon-box">
</div>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                你还未登陆，是否去登录
            </div>
            <div class="modal-footer">
                <button type="button" class="sanFast-btn back"
                        data-dismiss="modal">否
                </button>
                <button type="button" onclick="userLogin()" class="sanFast-btn login">
                    是
                </button>
            </div>
        </div>
    </div>
</div>


<script src="../../resource/js/jquery.min.js"></script>
<script src="../../resource/js/bootstrap.min.js"></script>
<script src="../../resource/js/commonjs.js"></script>
<script src="http://api.map.baidu.com/api?v=2.0&ak=qVrWQw9Vs8t7iPfG7bSj0137" type="text/javascript"></script>
<script type="text/javascript">
    var longitude = null;
    var latitude = null;
    var shop_id = null;
    var isGiving = null;
    var up_count = null;
    /* 初始化页面 */
    $(function() {
        shop_id = getArg("shop_id");
        viewShop();
        getPos();
        getShopExInfo();
    });
    function getShopExInfo() {
        var url = "/shops/getShopExInfo";
        var arg = {};
        arg.shop_id = shop_id;
        ajaxJsonp(url, arg, setShopExInfo);
    }
    function setShopExInfo(res) {
        console.log(res);
        up_count = res.data[shop_id].up_count;
    }
    /* 用户登陆事件 */
    function userLogin() {
        location.href = "../login/login.html?url=1";
    }
    /* 增加店铺浏览数 */
    function viewShop() {
        var shop_id = getArg('shop_id');
        var url = "/shops/viewShop";
        var arg = {};
        arg.id = shop_id;
        ajaxJsonp(url, arg);
    }
    /* 获取用户是否赞过店铺 */
    function getShopIsUserGiving() {
        var token = getCookie("token");
        if(token != -1 && token != undefined){
            var url = "/Shops/getShopIsUserGiving";
            var arg = {};
            arg.shop_id = shop_id;
            ajaxJsonp(url, arg, getGivingResult);
        }
    }
    /* 处理是否赞的结果 */
    function getGivingResult(res) {
        isGiving = res.data.is_giving;
        if(isGiving==1){
        $(".seller-prefer").addClass("user-prefer");
    }
    }
    /* 获取经纬度 */
    function getPos() {
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                longitude = r.point.lng;
                latitude = r.point.lat;
                getCoupons();
            }
            else {
                alert('failed'+this.getStatus());
            }
        },{enableHighAccuracy: true});
    }
    /* 获取商家优惠券 */
    function getCoupons() {
        var url = "/Shops/getShopsCouponList";
        var arg = {};
        shop_id = getArg("shop_id");

        arg.lat = latitude;
        arg.lon = longitude;
        arg.shop_id = shop_id;
        ajaxJsonp(url, arg, renderCouponList);
    }
    /* 渲染商家信息 */
    function renderCouponList(res) {
        var shop = res.data.shop_info;
        var coupons = res.data.coupon_list;
        /* 店家信息 */
        var html = '';
        var label = [];
        var distance = '';
        if(shop.juli) {
            distance = shop.juli.toFixed(1);
        }
        var bst = shop.business_start_time;
        var bet = shop.business_end_time;
        bst = calculateTime(bst);
        bet = calculateTime(bet);

        if(shop.juli < 1) {
            distance *= 1000;
            distance += 'm';
        } else {
            distance += 'km';
        }

        html += '<div class="coupon-list default-pad">';
        html += '<div class="coupon-left">';
        html += '<span class="vertical-align"></span><img class="seller-img" src="../../resource/images/seller-demo.png" />';
        html += '</div>';
        html += '<div class="coupon-detail">';
        html += '<strong class="seller-name">'+ shop.business_name + '(' + shop.name  + ')</strong>';
        for(var i = 0; i < shop.label_list.length; i++) {
            label.push(shop.label_list[i]);
        }
        label = label.join(" ");
        html += '<span class="seller-tag seller-detail">'+ label +' 人均'+ shop.ave_price +'</span>';
        html += '<span class="seller-dis seller-detail">' + distance +'</span>';
        html += '<span class="sale-time seller-detail">' + bst + "-" + bet + '<strong class="sale-time-target">营 业</strong></span>';
        html += '</div>';
        html += '<div class="seller-prefer">';
        html += '<strong class="seller-prefer-count">' + up_count + '</strong>';
        html += '</div>';
        html += '</div>';
        html += '<div class="seller-box default-pad">';
        html += '<address class="seller-location" data-lat="'+ shop.latitude +'" data-lon="'+ shop.longitude +'">';
        html += '<strong class="seller-location-detail">地址：'+ shop.address +'</strong><br>';
       /* html += '<abbr class="seller-phone" onclick="phoneCall()">电话：' + shop.telephone + '</abbr>';*/
        html += '<a class="seller-phone" onclick="phoneCall(this)">电话：' + shop.telephone + '</a>';
        html += '</address>';
        html += '</div>';
        $(".seller-content").append(html);
        setDivPosition();
        var length = coupons.length;
        html = '';
        var ids = [];
        for(var i = 0; i < length; i++) {
            var stt = new Date(coupons[i].start_time*1000).toLocaleDateString();
            var ext = new Date(coupons[i].expired_time*1000).toLocaleDateString();
            stt = stt.replace(/[年,月]/g,".");
            stt = stt.replace(/[日]/g,"");
            ext = ext.replace(/[年,月]/g,".");
            ext = ext.replace(/[日]/g,"");

            html += '<div class="seller-coupon-list">';
            html += '<div class="coupon-left">'+ coupons[i].discount + '折';
            html += '</div>';
            html += '<div class="coupon-mid">';
            html += '<span class="coupon-time">使用时间:'+ stt + '-'+ ext + '</span>';
            html += '<span class="coupon-total">共<strong class="coupon-count">'+ coupons[i].coupon_count +'张</strong>,余<srong class="coupon-count">'+ coupons[i].for_count +'</srong>张</srong></span>';
            html += '</div>';
            html += '<div class="coupon-right">';
            if(coupons[i].status == "1"){
                if(coupons[i].credit == 0) {
                    html += '<strong coupon-id="'+ coupons[i].id +'" class="coupon-operate get">领取</strong>';
                } else {
                    html += '<span class="coupon-code">'+ coupons[i].credit +'积分</span><strong coupon-id="' + coupons[i].id + '" class="coupon-operate get useCodeGet">兑换</strong>';
                }
            }
            html += '</div>';
            html += '<div class="coupon-bottom default-pad">';
            var remark = coupons[i].remark;
            remark = remark.split("<br/>");
            remark = remark.join(", ");
            html += '<strong class="coupon-tips">'+ remark +'</strong>';
            html += '</div></div>';
            ids.push(coupons[i].id);
        }
        $(".coupon-box").append(html);
        for(var i = 0; i < ids.length; i++) {
            getCouponExInfo(ids[i]);
        }
        $("#header").html('<a href="javascript:void(0)" class="nav-back">返回</a>'+ shop.business_name +'<span class=""></span>');
        isReceive();
        $(".loading").remove();
        evenBind();
        getShopIsUserGiving();
    }
    /* 判断是否可领取 */
    function isReceive() {
        var id = [];
        $(".coupon-operate").each(function () {
            id.push($(this).attr("coupon-id"));
        });
        id = id.join(",");
        var url = "/Coupon/isReceive";
        var arg = {};
        arg.id = id;
        ajaxJsonp(url, arg, hideDisabledCoupon);
    }
    /* 处理不可领 */
    function hideDisabledCoupon(res) {
        console.log(res);
        var data = res.data;
        for(var i =0; i<data.length; i++) {
            if(data[i].is_receive == 0) {
                $('.coupon-operate').each(function() {
                    if($(this).attr("coupon-id") == data[i].id) {
                        $(this).parent().empty().append('<strong class="coupon-operate view-coupon" onclick="viewCoupon(this)">查看</strong>');
                    }
                });
            }
        }
    }
    /* 查看个人发布优惠券 */
    function viewCoupon(target) {
        var distance = $(".seller-dis").text();
        location.href = "shop_detail.html?distance=" + distance + "&shop_id=" + shop_id;
    }
    /* 点赞 */
    function addShopUserGiving(is_cancel) {
        console.log(is_cancel);
        var url = "/Shops/addShopUserGiving";
        var arg = {};
        arg.shop_id = shop_id;
        arg.is_cancel = is_cancel;
        ajaxJsonp(url, arg, null, "post", givingFailed);
    }
    /* 点赞失败 */
    function givingFailed(res) {alert("点赞失败！")}
    /* 控制页面 */
    function setDivPosition() {
        var h = $(".coupon-detail").height() + 20;
        $(".coupon-list .coupon-left").height(h);
        $(".seller-prefer").height(h);
        $(".seller-prefer-count").css("marginTop",h/2 + 10);
        $(".seller-content").css("visibility","visible");
    }


    /* 没有登陆 */
    function withOutLoading(res) {
    var html = '';
        html += '<div class="modal-dialog">';
        html += '<div class="modal-content">';
        html += '<div class="modal-body">';
        html += '你还没有登陆，是否去登陆';
        html += '</div>';
        html += '<div class="modal-footer">';
        html += '<button type="button" class="sanFast-btn back" data-dismiss="modal">否';
        html += '</button>';
        html += '<button type="button" onclick="userLogin()" class="sanFast-btn get-coupon">';
        html += '是';
        html += '</button>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        $('#myModal').html(html);
        $(".modal-dialog").addClass("animate");
        $('#myModal').modal();
    }
    /* 领取优惠券 */
    function getCoupon(id) {
        var url = "/Coupon/Receive";
        var arg = {};
        arg.id = id;
        ajaxJsonp(url, arg, getCouponSuc, "get", withOutLoading);
        /* 领取成功 */
        function getCouponSuc(res) {
            var msg = "领取成功";
            showModal(msg);
            getCouponExInfo(id);
        }
    }
    function getCouponExInfo(id) {
        var url = "/shops/getShopExInfo";
        var arg = {};
        arg.coupon_id = id;
        ajaxJsonp(url, arg, setCouponExInfo);
        function setCouponExInfo(res) {
            console.log(res);
            var count = res.data[id].for_count;
            $(".coupon-operate").each(function() {
                if($(this).attr("coupon-id") == id) {
                    $(this).parent().parent().find(".coupon-count:eq(1)").text(count);
                }
            });
        }
    }
    /* 用户使用积分领取优惠券 */
    function userCodeGetCoupon(target) {
        var id = $(target).attr("data-id");
        getCoupon(id);
    }
    function evenBind() {
        $(".nav-back").click(function(){
            location.href = "../../index.html?url=1";
        });
        $(".get").click(function() {
            var id = $(this).attr("coupon-id");
            if($(this).hasClass("useCodeGet")) {
                var text = $(this).parent().find(".coupon-code").text();
                var html = '';
                    html += '<div class="modal-dialog">';
                    html += '<div class="modal-content">';
                    html += '<div class="modal-body">';
                    html += '你是否用'+ text +'兑换该优惠券';
                    html += '</div>';
                    html += '<div class="modal-footer">';
                    html += '<button type="button" class="sanFast-btn back"';
                    html += 'data-dismiss="modal">否';
                    html += '</button>';
                    html += '<button type="button" onclick="userCodeGetCoupon(this)" data-id="'+ id +'" class="sanFast-btn get-coupon">';
                    html += '是';
                    html += '</button>';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';
                $('#myModal').html(html);
                $('#myModal').modal("show");
            } else {
                getCoupon(id);
            }
        });
        $(".seller-prefer").click(function() {
            var token = getCookie("token");
            if(token==null||token==-1||token==undefined){
                $('#myModal').modal();
            }else{
                var is_cancel = '';
                if($(this).hasClass("user-prefer")) {
                    var count = $(".seller-prefer-count").text();
                    $(".seller-prefer-count").text(count - 1);
                    is_cancel = 1;
                } else {
                    var count = $(".seller-prefer-count").text();
                    count = parseInt(count) + 1;
                    $(".seller-prefer-count").text(count);
                    is_cancel = 0;
                }
                $(this).toggleClass("user-prefer");
                addShopUserGiving(is_cancel);
            }

        });
        /*$(".seller-location").click(function (e) {
            if($(e.target).hasClass("seller-phone")) {
                e.stopPropagation();
            } else {
                var lat = $(this).attr("data-lat");
                var lon = $(this).attr("data-lon");
                var name = $(".seller-name").text();
                var url = "viewSellerInMap.html?lat=" + lat + "&lon=" + lon + "&name=" + name;
                location.href = url;
            }
        });*/
        $(".seller-location").click(function (e) {
            var lat = $(this).attr("data-lat");
            var lon = $(this).attr("data-lon");
            var name = $(".seller-name").text();
            var url = "viewSellerInMap.html?lat=" + lat + "&lon=" + lon + "&name=" + name;
            location.href = url;
        });
    }

    function phoneCall(target){
        stopEventBubble();
        console.log($(target).text().length);
        var telNum = $(target).text().substr(3,13);
        console.log($(target).text().substr(3,13));
        location.href= 'tel://' + telNum;
    }
</script>
</body>
</html>